package com.weiqiao.mall.rest;

import com.weiqiao.aop.log.Log;
import com.weiqiao.mall.service.IAppUserService;
import com.weiqiao.utils.StringUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 接收上传表格信息，控制层
 */
@RestController
@RequestMapping("/excel-upload")
public class ExcelUploadController {

    // 客户管理控制层
    @Autowired
    private IAppUserService appUserService;

    @Log("员工信息上传")
    @PostMapping("/workers-info-upload")
    public ResponseEntity workersInfoUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        int companyId = Integer.parseInt(request.getParameter("company_id"));
        boolean result = false;
        Map<String, String> map = new HashMap();
        if (!StringUtils.isBlank(file)) {
            // 文件名
            String fileName = file.getOriginalFilename();
            // 获取后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            InputStream inputstream = null;
            if (".xls".equals(suffixName) || ".xlsx".equals(suffixName)) {
                try {
                    inputstream = file.getInputStream();
                    // 导入员工数据保存至数据库
                    result = appUserService.importWorkersInfo(companyId,inputstream);
                } catch (IllegalStateException | IOException e) {
                    e.printStackTrace();
                } finally {
                    IOUtils.closeQuietly(inputstream);
                }
            }
        }
        return new ResponseEntity(result, HttpStatus.OK);
    }
}
